import { inWechat } from '@/utils'
import Taro from '@tarojs/taro'
import { useCallback } from 'react'
import { useUserStore } from '@/common/hox/userStore'

const timeout = 10 * 60 * 1000
const storageKey = 'needPhoneTimeout'

function useNeedPhone() {
    const { userInfo } = useUserStore()

    const checkNeed = useCallback(() => {
        if (!inWechat()) return false
        if (userInfo?.isBindPhone) return false
        const { time = null } = Taro.getStorageSync(storageKey)
        return time ? ((new Date().getTime() - time) > timeout) : true
    }, [userInfo?.isBindPhone])

    const redirect = useCallback((navUrl?: string) => {
        // if (!inWechat()) return
        let url = `/pages/login/index`
        if (navUrl) url += `?navUrl=${encodeURIComponent(navUrl)}`
        Taro.navigateTo({ url })
    }, [])

    const refreshTime = useCallback(() => {
        Taro.setStorageSync(storageKey, { time: new Date().getTime() })
    }, [])

    return { checkNeed, redirect, storageKey, refreshTime }
}

export default useNeedPhone